package Day15;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 客户端程序
 */
public class ChatClient {

    //创建一个线程池
    static ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * @param serverIp   服务器IP地址
     * @param serverPort 服务器监听的端口
     */
    public static Socket startClient(String serverIp, int serverPort) throws Exception {
        Socket client = null;
        client = new Socket(serverIp, serverPort);
        return client;
    }

    //程序入口
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            Socket socket = new Socket("localhost", 8080);
            // 创建发送信息的线程
            new ClientSend(socket).start();
            // 创建接收信息的线程
            new ClientReceive(socket).start();
        } catch (Exception ex) {
            System.out.println("无法连接服务器，请确保聊天室已启动,错误信息为：" + ex.getMessage());
        }
    }

    //客户端接收信息的线程
    public static class ClientReceive extends Thread {
        private Socket socket;

        public ClientReceive(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                // 按行接收信息
                String line = "";
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 客户端向服务端发送信息的线程
     */
    public static class ClientSend extends Thread {
        private Scanner scanner;
        private Socket socket;

        public ClientSend(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            scanner = new Scanner(System.in);
            try {
                PrintStream ps = new PrintStream(socket.getOutputStream());
                String line = "";
                while ((line = scanner.nextLine()) != null) {
                    ps.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}